<template>
  <div class="container">
    <el-card style="position: relative; height: 700px">
      <div>
        <h2 class="title">新建通知</h2>
        <div class="page-close-box">
          <el-button link type="primary" @click="$router.go(-1)">
            <el-icon><Close /></el-icon>
          </el-button>
        </div>
      </div>
      <el-form
        :inline="true"
        :model="formInline"
        :rules="rules"
        class="demo-form-inline"
      >
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="通知时间:" prop="notifyTime">
              <el-date-picker
                v-model="formInline.notifyTime"
                type="datetime"
                placeholder="选择日期"
                clearable
                format="YYYY-MM-DD HH:mm:ss"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="通知类型:" prop="notifyTypeId">
              <el-select
                v-model="formInline.notifyTypeId"
                placeholder="请选择"
                clearable
                @change="tabType"
              >
                <el-option
                  v-for="item in options"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item
          v-if="formInline.notifyTypeId === '1'"
          label="会议时间:"
          prop="meetingTime"
        >
          <el-date-picker
            v-model="formInline.meetingTime"
            type="datetime"
            placeholder="选择日期"
            clearable
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
          />
        </el-form-item>
        <el-form-item
          v-if="formInline.notifyTypeId === '1'"
          label="会议名称:"
          prop="meetingName"
        >
          <el-input
            class="input-item"
            v-model="formInline.meetingName"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <el-form :model="formInline" :rules="rules" class="demo-form-inline">
        <el-form-item label="通知内容:" prop="notifyText">
          <el-input
            v-model="formInline.notifyText"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
        <el-form-item label="通知附件/图片:">
          <fileupload
            @update:modelValue="handleModelValueFile"
            :modelValue="formInline.msgFile"
          ></fileupload>
        </el-form-item>
        <el-form-item
          style="display: flex; align-items: center"
          label="通知范围:"
        >
          <div class="name_content">
            <el-tag
              v-for="(item, index) in formInline.notifyWide"
              :key="index"
              v-if="formInline.notifyWide !== 0"
              type="success"
              :closable="userStore.userId !==  item.userId"
              @close="handleDelOpportunitiesApprover(item, index)"
            >
              {{ item.nickName }}
            </el-tag>
          </div>
          <span @click="dialogTableVisible = true">添加通知范围</span>
        </el-form-item>
      </el-form>
      <el-dialog
        v-model="dialogTableVisible"
        title="通知范围"
        width="800"
        append-to-body
        center
      >
        <div style="display: flex; justify-content: space-between">
          <el-form
            :inline="true"
            :model="formInline"
            label-width="75px"
            size="mini"
            label-position="right"
            style="display: flex"
          >
            <el-form-item label="员工姓名">
              <el-input
                v-model="formInline.nickName"
                placeholder="员工姓名"
                :clearable="true"
              ></el-input>
            </el-form-item>
            <el-form-item label="所属部门">
              <el-cascader
                class="input-item"
                v-model="formInline.deptId"
                :clearable="true"
                placeholder="所属部门"
                :props="dropdownprops"
                :options="dropdownList"
              >
              </el-cascader>
            </el-form-item>
          </el-form>
          <el-button type="primary" @click="enquiries">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </div>
        <div>
          <el-table
            :data="gridData"
            size="mini"
            header-cell-class-name="table-header-gray"
            style="width: 100%"
          >
            <el-table-column
              align="center"
              type="index"
              width="50"
              label="序号"
            />
            <el-table-column align="center" prop="nickName" label="用户名" />
            <el-table-column align="center" prop="userName" label="员工姓名" />
            <el-table-column align="center" prop="dept.deptName" label="部门" />
            <el-table-column align="center" prop="manipulate" label="操作">
              <template #default="scope">
                <el-button
                  type="primary"
                  @click="addNotifier(scope.row)"
                  size="mini"
                  v-if="!scope.row.check"
                  >选择</el-button
                >
                <el-button
                  type="danger"
                  @click="lifted(scope.row)"
                  size="mini"
                  v-if="scope.row.check"
                  >取消</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <el-row type="flex" justify="end" style="margin-top: 10px">
            <el-pagination
              background
              @size-change="handleSizeChangeGroup"
              @current-change="handleCurrentChangeGroup"
              :current-page="pageNum"
              :page-size="pageSize"
              :page-sizes="[10, 20, 50, 100]"
              layout="total, prev, pager, next, sizes"
              :total="total"
            ></el-pagination>
          </el-row>
        </div>
      </el-dialog>
      <div class="Cancel_ok">
        <el-button @click="$router.go(-1)">取消</el-button>
        <el-button @click="ok" type="primary">确定</el-button>
      </div>
    </el-card>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import fileupload from "@/components/FileUpload";
import { selectsPeoples, deptNameApi } from "@/api/project/conversion";
import { notificationAddApi } from "@/api/messageNotifications/notificationsList";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import useUserStore from "@/store/modules/user";
const router = useRouter();
const route = useRoute();
const approverRef = ref();
const userStore = useUserStore();

const options = [
  {
    value: "1",
    label: "会议",
  },
  {
    value: "2",
    label: "项目",
  },
  {
    value: "3",
    label: "其他",
  },
];
const formInline = reactive({
  notifyTypeId: "", //  通知类型
  notifyTime: "", //  选择通知时间
  notifyText: "", //  通知内容
  notifyWide: [], //  通知范围
  msgFile: [], //  通知附件
  nickName: "", // 员工姓名
  meetingName: "", // 会议名称
  meetingTime: "", // 会议时间
  deptId: "", // 所属部门Id
});

const rules = reactive({
  notifyTypeId: [
    { required: true, message: "请选择通知类型", trigger: "change" },
  ],
  notifyTime: [
    { required: true, message: "请选择通知时间", trigger: "change" },
  ],
  notifyText: [{ required: true, message: "请输入通知内容", trigger: "blur" }],
  meetingName: [{ required: true, message: "请输入会议名称", trigger: "blur" }],
  meetingTime: [
    { required: true, message: "请输选择会议时间", trigger: "change" },
  ],
});
// 所属部门下拉
const dropdownList = ref([]);
// 获取所属部门名称
const getdeptName = async () => {
  const res = await deptNameApi();
  console.log(res);
  if (res.code === 200) {
    dropdownList.value = res.data;
  }
};
// 所属部门下拉配置
let dropdownprops = {
  value: "deptId",
  label: "deptName",
  emitPath: false,
};
const dialogTableVisible = ref(false);
// 添加附件
const handleModelValueFile = (val, result, operationType) => {
  if (operationType === "success") {
    if (result) {
      formInline.msgFile = [];
      result.forEach((item)=>{
        formInline.msgFile.push(item);
      });
    }
  } else if (operationType === "delete") {
    formInline.msgFile.splice(result, 1);
  }
};
// 表格数据
const gridData = ref([]);
const pageNum = ref(1);
const pageSize = ref(999999);
const total = ref(0);
const currentPerson = ref();
// 获取通知列表
const getNoticeList = async () => {
  let params = {
    pageNum: pageNum.value,
    pageSize: pageSize.value,
    nickName: formInline.nickName,
    deptId: formInline.deptId,
  };
  const res = await selectsPeoples(params);
  if (res.code === 200 && res.rows.length >= 0) {
    gridData.value = res.rows;
    // 默认进来第一次选择人
    currentPerson.value = gridData.value.find(
      (it) => userStore.userId === it.userId
    );
    if (currentPerson.value) {
      currentPerson.value.check = true;
    }
    // console.log(currentPerson.value,'---currentPerson---',userStore.userId)

    total.value = Number(res.total);
  }
};
// 查询
const enquiries = () => {
  getNoticeList();
};
// 重置
const reset = () => {
  (formInline.nickName = ""), (formInline.deptId = "");
  getNoticeList();
};
// 切换每页条数
const handleSizeChangeGroup = (val) => {
  pageSize.value = val;
  getNoticeList();
};
// 切换页码
const handleCurrentChangeGroup = (val) => {
  pageNum.value = val;
  getNoticeList();
};
// 选择
const addNotifier = (row) => {
  row.check = true;
  formInline.notifyWide.push(row);
};
// 取消
const lifted = (row) => {
  if (userStore.userId === row.userId) {
    row.check = true;
  } else {
    row.check = false;
    let index = formInline.notifyWide.findIndex(
      (item) => item.userId === row.userId
    );
    formInline.notifyWide.splice(index, 1);
  }

  // console.log(formInline.notifyWide, "-----123---");
};
// 删除当前条数据
const handleDelOpportunitiesApprover = (item, index) => {
  formInline.notifyWide.splice(index, 1);
  gridData.value.forEach((it) => {
    if (it.userId === item.userId) {
      item.check = false;
      it.check = item.check;
    }
  });
};
const ok = async () => {
  let data = {
    msgType: formInline.notifyTypeId,
    notifyTime: formInline.notifyTime,
    msgText: formInline.notifyText,
    notifyWide: formInline.notifyWide.map((item) => item.userId),
    msgFile: formInline.msgFile,
    meetingName: formInline.meetingName,
    meetingTime: formInline.meetingTime,
  };
  if (data.notifyWide.length === 0) {
    ElMessage.error("请添加通知范围");
    return;
  }
  const res = await notificationAddApi(data);
  console.log(res);
  if (res.code === 200) {
    ElMessage.success("添加成功");
    router.go(-1);
  }
};

onMounted(async () => {
  await getNoticeList();
  await getdeptName();

  setTimeout(() => {
    if (formInline.notifyWide=== null) {
      formInline.notifyWide = [];
    }
    if (route.query.name === "1") {
      formInline.notifyWide.push(currentPerson.value);
      // console.log( formInline.notifyWide,'--- formInline.notifyWide--')
    }
  }, 1000);
});
</script>
<style scoped lang="scss">
.container {
  padding: 20px;
  .demo-form-inline {
    padding: 10px 0 0 30px;
  }
  .title {
    font-weight: 600;
    color: #383838;
    padding-bottom: 5px;
    margin-bottom: 10px;
  }
  .page-close-box {
    position: absolute;
    background: #0092ff;
    transform: rotate(45deg);
    height: 50px;
    width: 50px;
    right: -25px;
    top: -25px;
    text-align: center;

    .el-button {
      transform: rotate(-45deg);
      color: white;
      margin-top: 30px;
    }
  }
  span {
    color: #409eff;
    margin-left: 10px;
    &:hover {
      cursor: pointer;
    }
  }
  .Cancel_ok {
    position: absolute;
    left: 50%;
    bottom: 50px;
    transform: translateX(-50%);
  }
}
</style>
